package com.it.data.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.it.data.network.req.BaseDto
import com.it.data.network.req.UploadListDto
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File
import java.lang.reflect.Type

/**
 * HttpUtil 工具类，把vo转换成map
 *
 * @author weishixiong
 * @Time 2018-03-19
 */
object HttpParamUtil {

    fun convertVo2Json(dto: BaseDto): RequestBody {
        val maps = convertVo2Params(dto)
        val jsonObject = JSONObject(maps)
        return RequestBody.create(
            "application/json".toMediaType(),
            "{\"data\":${jsonObject}}"
        )
    }

    fun convertVo2Params(dto: BaseDto): Map<String, String> {
        val gson = Gson()
        val type: Type = object : TypeToken<Map<String, String>>() {}.type
        return gson.fromJson(gson.toJson(dto), type)
    }

    /**
     * 多文件转换为 Map<String, RequestBody> bodyMap
     *
     * @param files
     * @param mediaType 文件类型
     * @return
     */
    fun convertVo2BodyMap(files: List<File>, mediaType: String): Map<String, RequestBody> {
        val bodyMap = mutableMapOf<String, RequestBody>()
        for (i in files.indices) {
            bodyMap["file$i\"; filename=\"${files[i].name}"] =
                RequestBody.create(mediaType.toMediaType(), files[i])
        }
        return bodyMap
    }

    /**
     * 一次性上传所有的对象文件
     * 数组对象，对象中包含文件数组
     * files转换为MultipartBody
     *
     * @param voList
     * @return
     */
    fun filesToMultipartBody(voList: List<UploadListDto>, mediaType: String): MultipartBody {
        val builder = MultipartBody.Builder()
        for (i in voList.indices) {
            val applyId = "lists[$i].${voList[i].visitApplyId}"
            val recordTime = "lists[$i].${voList[i].recordTime}"
            val address = "lists[$i].${voList[i].visitorAddress}"
            builder.addFormDataPart(applyId, voList[i].visitApplyId)
            builder.addFormDataPart(recordTime, voList[i].recordTime)
            builder.addFormDataPart(address, voList[i].visitorAddress)

            for (j in voList[i].getuFile().indices) {
                val requestBody =
                    RequestBody.create(mediaType.toMediaType(), voList[i].getuFile()[j])
                builder.addFormDataPart(
                    "lists[$i].uFile",
                    voList[i].getuFile()[j].name,
                    requestBody
                )
            }
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    /**
     * 上传单个对象的文件
     * 对象中包含文件数组
     * files转换为MultipartBody
     *
     * @param files
     * @return
     */
    fun filesToMultipartBody(vo: BaseDto?, files: List<File>, mediaType: String): MultipartBody {
        val builder = MultipartBody.Builder()
        for (file in files) {
            val requestBody = RequestBody.create(mediaType.toMediaType(), file)
            builder.addFormDataPart("files", file.name, requestBody)
        }
        vo?.let {
            val map = convertVo2Params(it)
            for ((key, value) in map) {
                builder.addFormDataPart(key, value)
            }
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    /**
     * @param files
     * @return
     */
    fun filesToMultipartBodyParts(
        fileName: String,
        files: List<File>,
        mediaType: String
    ): MultipartBody {
        val builder = MultipartBody.Builder()
        for (file in files) {
            val requestBody = RequestBody.create(mediaType.toMediaType(), file)
            builder.addFormDataPart(fileName, file.name, requestBody)
        }
        builder.setType(MultipartBody.FORM)
        return builder.build()
    }

    fun buildUrl(
        baseUrl: String,
        queryParams: Map<String, String?> = emptyMap()
    ): String {


        // 如果没有查询参数，直接返回路径
        if (queryParams.isEmpty()) return baseUrl

        // 构建查询参数部分
        val query = queryParams.filterValues { it != null }
            .map { (key, value) -> "$key=$value" }
            .joinToString("&")

        // 合并路径和查询参数
        return if (query.isEmpty()) baseUrl else "$baseUrl?$query"
    }

    // 动态构建URL的工具函数
    fun buildStationListUrl(
        paramList: List<String>,
        url: String
    ): String {
        return url + "/" + paramList.joinToString("/")
    }


}